<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="账号" prop="account">
        <el-input disabled :value="form.account" />
      </el-form-item>
      <el-form-item label="角色" prop="roleAuthList">
        <div ref="treeBox" style="max-height: 300px; overflow: auto">
          <el-checkbox-group v-model="form.roleAuthList">
            <el-checkbox
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="isSaving" type="primary" @click="save">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { getRoles, assignRole, getRolesById } from '@/api/role'
  import { Loading } from 'element-ui'

  export default {
    name: 'RoleAssign',
    props: {
      treeData: {
        type: Array,
        default: () => [],
        require: true,
      },
    },
    data() {
      return {
        defaultProps: {
          children: 'childList',
          label: 'name',
        },
        parentName: '',
        form: {
          account: '',
          id: '',
          roleAuthList: [],
        },
        roleList: [],
        roleJson: {},
        rules: {},
        title: '',
        dialogFormVisible: false,
        isSaving: false,
      }
    },
    created() {},
    methods: {
      getRoleList() {
        const loadingInstance = Loading.service({ target: this.$refs.treeBox })
        getRoles()
          .then((res) => {
            if (
              res &&
              res.status === 0 &&
              res.data &&
              Array.isArray(res.data.list)
            ) {
              const arr = []
              const json = {}
              res.data.list.forEach((v) => {
                arr.push({ label: v.name, value: v.id })
                json[v.name] = v.id
              })
              this.roleJson = json
              this.roleList = arr
              getRolesById(this.form.id)
                .then((rs) => {
                  if (rs && Array.isArray(rs.data)) {
                    this.form.roleAuthList = rs.data.map((v) => {
                      return v.name
                    })
                  }
                  loadingInstance.close()
                })
                .catch((e) => {
                  console.log(e)
                  loadingInstance.close()
                })
            } else {
              loadingInstance.close()
            }
          })
          .catch((err) => {
            console.log(err)
            loadingInstance.close()
          })
      },
      handleNodeClick(node) {
        this.parentName = node.name
        this.form.pid = node.id
      },
      showEdit(row) {
        // console.log(row)
        this.form.account = row.account
        this.form.id = row.id
        this.title = '分配角色'
        this.getRoleList()
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.parentName = ''
      },
      async save() {
        try {
          this.isSaving = true
          const res = await assignRole({
            userId: this.form.id,
            roleList: this.form.roleAuthList.map((v) => this.roleJson[v]),
          })
          let successMsg = '分配成功'
          let errorMsg = '分配失败'
          if (res && res.status === 0) {
            this.$baseMessage(successMsg, 'success', 'vab-hey-message-success')
            // this.$emit('fetch-data')
            this.close()
          } else {
            this.$baseMessage(
              res ? res.msg : errorMsg,
              'error',
              'vab-hey-message-error'
            )
          }
        } catch (e) {
          console.log(e)
          this.$baseMessage(
            e ? e.message : '操作失败',
            'error',
            'vab-hey-message-error'
          )
        }
        this.isSaving = false
      },
    },
  }
</script>
